package com.hangyutech.strelitzia.page;

/**
 * Created by Andy on 19/11/8.
 */
public class PageUtil {

    private static final int minPageSize = 1;
    private static final int maxPageSize = 100;
    private static final int defaultPageSize = 20;

    private PageUtil() {
    }

    /**
     * 页面输入数据转换
     *
     * @param page
     */
    private static void parseInputPageInfo(PageInfo page) {
        verifyPage(page);
        page.setCursor((page.getPageNo() - 1) * page.getPageSize());
    }

    /**
     * 数据库返回数据转换
     *
     * @param page
     */
    private static void parseOutputPageInfo(PageInfo page) {
        verifyPage(page);
        if (page.getTotalRecord() / page.getPageSize() < 1) {
            page.setTotalPage(1);
        } else if (page.getTotalRecord() % page.getPageSize() == 0) {
            page.setTotalPage(page.getTotalRecord() / page.getPageSize());
        } else {
            page.setTotalPage(page.getTotalRecord() / page.getPageSize() + 1);
        }
    }

    private static void verifyPage(PageInfo page) {

        if (page.getTotalRecord() < 0) page.setTotalRecord(0);

        if (page.getTotalPage() < 1) page.setTotalPage(1);

        if (page.getPageNo() < 1) page.setPageNo(1);

        if (page.cursor() < 0) page.setCursor(0);

        if (page.getPageSize() < minPageSize || page.getPageSize() > maxPageSize) {
            page.setPageSize(defaultPageSize);
        }
    }

    public static PagingBounds toPagingBounds(PageInfo pageInfo) {
        parseInputPageInfo(pageInfo);
        PagingBounds bounds = new PagingBounds(pageInfo.cursor(), pageInfo.getPageSize());
        pageInfo.setBounds(bounds);
        return bounds;
    }

    public static void outputProcess(PageInfo pageInfo) {
        if (pageInfo.bounds() != null) {
            pageInfo.setTotalRecord(((PagingBounds) pageInfo.bounds()).getTotal());
            parseOutputPageInfo(pageInfo);
            pageInfo.setBounds(null);
        }
    }


}
